layui.define(['layer','form','table','dtree'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        dtree = layui.dtree,
        table = layui.table,
        modeutils = {
            /**
             * 弹窗封装
             * @param modeId 弹窗容器id
             * @param config 容器参数：
             *  type 打开类型：show -> 详情；add -> 添加，edit -->编辑；
             *  title 模态框标题:默认是详情；
             *  rSetID 重置按钮，如果不传，默认'#LAY_RSET_BTN'；
             *  width 模态框宽度；
             *  height 模态框高度；
             *  skin：模态框自定义皮肤，默认是内置皮肤；
             */
            openMode: function (config, modeId) {
                var type = config.type ? config.type : 'show';
                var title = config.title ? config.title : '详情';
                var rSetID = config.rSetID ? config.rSetID : '#LAY_RSET_BTN';
                var width = config.width ? config.width : '60%';
                var height = config.height ? config.height : '60%';
                var skin = config.skin ? config.skin : 'layui-layer-molv';
                if ('add' === type) {
                    $(rSetID).attr("style", "display:block;");
                    $(rSetID).click();
                } else if ('edit' === type) {
                    $(rSetID).attr("style", "display:none;");
                } else if ('show' === type) {
                    //可能有相关操作
                }
                layer.open({
                    type: 1
                    , skin: skin  //引入自定义样式
                    , title: title
                    , content: $('#' + modeId) //'sys/sysLoginLog/sysLoginLog-add.jsp'
                    , shadeClose: true
                    , area: [width, height]
                    , maxmin: true //最大小化窗口
                    , fixed: true //固定窗口
                    , scrollbar: true //滚动条
                })
            },

            /**
             * ajax请求封装
             * @param config 参数属性：
             *  type 请求类型，默认POST;
             *  url 请求地址;
             *  data 请求参数。默认为空;
             *  dataType 请求返回类型，默认为json;
             *  async 是否异步请求，默认为true;
             *  success 请求成功回调函数，默认控制台打印结果;
             *  error 错误时的回调函数，默认控制台打印;
             *  complete 请求完成后的回调函数，默认不操作
             */
            post: function (config) {
                var type = config.type ? config.type : 'POST';
                var url = config.url ? config.url : '';
                var data = config.data ? config.data : '';
                var dataType = config.dataType ? config.dataType : 'json';
                var async = config.async ? config.async : 'true';
                var success = config.success;
                var error = config.error;
                var complete = config.complete;
                var contentType = config.contentType? config.contentType:'application/x-www-form-urlencoded; charset=UTF-8';
                if('json'===config.dataType){
                    //json可以定义自己的contentType
                    contentType = 'application/json;charset=utf-8';
                }
                $.ajax({
                    type: type,
                    url: url,//发送请求
                    data: data,
                    async: async,
                    contentType:contentType,
                    dataType: dataType,
                    success: function (result) {
                        if (typeof success === 'function') {
                            success(result)
                        } else {
                            console.log(result)
                        }
                    },
                    error: function (err) {
                        if (typeof error === 'function') {
                            error(err)
                        } else {
                            console.error(err)
                        }
                    },
                    complete: function (res) {
                        if (typeof complete === 'function') {
                            complete(res)
                        }
                    }
                })
            },

            open: function(modelId,postConfig,modelConfig) {
                var config = {
                    success: function (res) {
                        if (res.success) {
                            var formData = res.data;
                            formData["roleCreateDt"] = formData.roleCreateDt ? formatTimeG(formData.roleCreateDt,'yyyy-MM-dd hh:mm:ss') : "";
                            formData["updateTime"] = formData.updateTime ? formatTime(formData.updateTime,'yyyy-MM-dd hh:mm:ss') : "";
                            form.val(modelConfig.filter,formData);
                           // postConfig.statusM.set([res.data.status]);
                            form.render();
                            modeutils.openMode(modelConfig, modelId);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function (err) {
                        layer.msg("请求错误，请重试", {icon: 2});
                    }
                };
                $.extend(config,postConfig);
                this.post(config);
            },

            delete:function (type,data,url) {
                if("delete" === type){
                    layer.confirm('是否确定删除选择的数据？', {
                        title:"询问",
                        btn: ['确定','取消'] //按钮
                    }, function() {
                        var config = {
                            url:url,
                            data:data,
                            success: function (res) {
                                if(res.success){
                                    layer.msg(res.msg, {icon: 1});
                                    table.reload('entityTableInfo',{});
                                }else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            },
                            error:function (err) {
                                layer.msg("请求错误，请重试", {icon: 2});
                            }
                        };
                        modeutils.post(config);
                    })
                }else if("batchDelete" === type){
                    if(data.ids.length < 1){
                        layer.msg('请择数据进行删除！');
                    }else{
                        layer.confirm('是否确定删除选择的数据？', {
                            title:"询问",
                            btn: ['确定','取消'] //按钮
                        }, function(){
                            var config = {
                                url:url,
                                data:data,
                                success: function (res) {
                                    table.reload('entityTableInfo',{});
                                },
                                error:function (err) {
                                    layer.msg("请求错误，请重试", {icon: 2});
                                }
                            }
                            modeutils.post(config);
                        })
                    }
                }
            },

            /**
             *
             * @param config 参数属性
             * title 弹窗标题
             * treeId 树的唯一标识
             * valueId 选框的div id
             * textId 选框id描述值div id
             * url 数据源地址
             * menubarTips 工具栏属性
             */
            dtree:function (config) {
                var menubarTips = {
                    toolbar: [],  //依附工具栏
                    group: ["moveDown", "moveUp", "refresh", "searchNode"], //按钮组
                    freedom: [] // 自由指定
                };
                var title = config.title ? config.title : "请选择";
                var treeId = config.treeId ? config.treeId : "DtreeId_"+(new Date()).getTime();
                var valueId = config.valueId ? config.valueId : "valueId_"+(new Date()).getTime();
                var textId = config.textId ? config.textId : "textId_"+(new Date()).getTime();
                var url = config.url ? config.url : "";
                var menubarTips = config.menubarTips ? config.menubarTips : menubarTips;
                var fun = config.function ? config.function : "";

                layer.open({
                    type: 1, //type:0 也行
                    skin: 'layer-ext-mySkin',  //引入自定义样式
                    title: title,
                    area: ["400px", "60%"],
                    content: '<ul id="'+treeId+'" class="dtree" data-id="0"></ul>',
                     btn: ['确认'],
                    success: function(layero, index){
                        var DTree = dtree.render({
                            menubar:true,
                            menubarTips :menubarTips,
                            response:{basicData:"attributes"},
                            icon: "2",
                            skin:"layui",
                            obj: $(layero).find("#" + treeId),
                            url: url,
                            done: function(data, obj){  //使用异步加载回调
                                var reportId = $("#" + valueId).val();
                                dtree.dataInit(treeId, reportId); // 初始化值
                               // var param = dtree.getNowParam(treeId); //获取当前选择的值
                               // console.log(param);
                            }
                        });

                        dtree.on("nodedblclick('"+treeId+"')", function(obj){
                            $("#" + valueId).val(obj.param.nodeId);
                            $("#" + textId).val(obj.param.context);
                            if (typeof fun === 'function') {
                                fun(obj.param)
                            } else {
                                console.log(obj.param)
                            }
                            layer.close(index);
                        });
                    },
                    yes: function(index, layero) {
                        var param = dtree.getNowParam(treeId); // 获取当前选中节点
                        $("#" + valueId).val(param.nodeId);
                        $("#" + textId).val(param.context);
                        if (typeof fun === 'function') {
                            fun(param)
                        } else {
                            console.log(obj.param)
                        }
                        layer.close(index);
                    }
                });
            },

            /**
             * layui原生select
             * @param config 属性说明
             * selectId 下拉列表ID
             * dicts 数据字典数据列表[]
             * typename 字典名称string
             */
            select:function (config) {
                var dictsDefult = [{"id":"25","text":"禁用","value":"0","parentid":null,"status":1,"leaf":true,"selected":false,"children":null,"expanded":true,"typename":"sys_base_status_val"}, {"id":"24","text":"正常","value":"1","parentid":null,"status":1,"leaf":true, "selected":true,"children":null,"expanded":true, "typename":"sys_base_status_val"}];
                var selectId = config.selectId ? config.selectId : "selectId_" + (new Date()).getTime();
                var dicts = config.dicts ? config.dicts : dictsDefult;
                var typename = config.typename ? config.typename : "sys_base_status_val";
                //获取下列列表数据
                var selectData = getDaictByTypeName(dicts,typename);
                var selectHtml = "<option ></option>";
                /*for(var n in selectData){
                    if(selectData[n].selected){ //设置默认值
                        selectHtml += "<option value=\""+selectData[n].value+"\" selected=\"\">"+selectData[n].text+"</option>";
                    }else{
                        selectHtml += "<option value=\""+selectData[n].value+"\">"+selectData[n].text+"</option>";
                    }
                }*/
                for (var i = 0; i < selectData.length; i++) {
                    if (selectData[i].status !== 0) {
                        if (selectData[i].selected) { //设置默认值
                            selectHtml += "<option value=\"" + selectData[i].value + "\" selected=\"\">" + selectData[i].text + "</option>";
                        } else {
                            selectHtml += "<option value=\"" + selectData[i].value + "\">" + selectData[i].text + "</option>";
                        }
                    }
                }

                console.log(selectHtml);
                $("#"+selectId).html(selectHtml);
            }
        };
    exports('modeutils', modeutils);
});
    /*时间格式化*/
    function formatTimeG(time, format){
    var date = new Date(time);
    var year = (date.getYear() < 1900) ? date.getYear() + 1900 : date.getYear();
    var o = {
        "M+": date.getMonth() + 1, // month
        "d+": date.getDate(), // day
        "h+": date.getHours(), // hour
        "m+": date.getMinutes(), // minute
        "ss": date.getSeconds(), // second
        "ms": date.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (year + "").substr(4
            - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
